package com.oauth.application.client.ui;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DecoratedStackPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.oauth.application.client.beans.ApplicationClientBean;
import com.oauth.application.client.rpc.ApplicationRemoteServiceAsync;

public class BrowseWindow extends Composite {

	private static BrowseWindowUiBinder uiBinder = GWT.create(BrowseWindowUiBinder.class);

	interface BrowseWindowUiBinder extends UiBinder<DecoratedStackPanel, BrowseWindow> {
	}

	@UiField
	DecoratedStackPanel stackPanel;

	@UiField
	VerticalPanel vPanel;

	public BrowseWindow() {
		initWidget(uiBinder.createAndBindUi(this));
		stackPanel.setStackText(0, "<div class=\"stackText\">Available Applications</div>", true);
	}

	private ApplicationRemoteServiceAsync applicationAddService;

	public Grid addBrowseWidget(List<ApplicationClientBean> pResult) {

		Grid grid = new Grid(4, 2);
		int row = 0, column = 0;
		for (ApplicationClientBean clientBean : pResult) {
			grid.setWidget(row, column, getApplicationPanel(clientBean));
			grid.getCellFormatter().setWidth(row, column, "2px");
			row = column == 1 ? ++row : row;
			column = column == 0 ? 1 : 0;

		}

		if (pResult.isEmpty()) {
			grid
					.setWidget(
							row,
							column,
							new HTML(
									"<div align=center><b>There are no applications to add.</b><br/> Many new applications will be added shortly.</div>"));
		}
		return grid;
	}

	private Widget getApplicationPanel(ApplicationClientBean pClientBean) {
		ApplicationPanel appPanel = new ApplicationPanel();
		appPanel.setApplicationBean(pClientBean);
		appPanel.setService(applicationAddService);
		return appPanel;
	}

	public void initBrowseWidget(List<ApplicationClientBean> pResult,
			ApplicationRemoteServiceAsync pApplicationAddService) {
		applicationAddService = pApplicationAddService;
		vPanel.add(addBrowseWidget(pResult));
	}

}